﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ABELGX
{
    public abstract class CarCmd
    {
        public const byte CMD_HEART = 0x01;
        public const byte CMD_SPEED = 0x02;
        public const byte CMD_WATER = 0x03;
        public const byte CMD_PTZ = 0x04;
        public const byte CMD_COMMON = 0x05;
        public const byte CMD_PARAM = 0x06;
        public const byte CMD_ARM = 0x07;
        public const byte CMD_SUBS = 0x08;
        public const byte CMD_BOX = 0x09;

        public const byte HEADER0 = 0xAA;
        public const byte HEADER1 = 0x55;
        public CmdSet Set { get; }
        public bool Enable { get; set; } = true;
        public byte Func { get; }
        public byte[] Cmd { get; set; }
        public DateTime SendTime { get; set; } = DateTime.Now;
        public bool CanSend => Set != null && Set.Interval > 0 && DateTime.Now.Subtract(SendTime).TotalMilliseconds > Set.Interval;
        public CarCmd(CmdSet set, int length)
        {
            Set = set;
            Func = (byte)set.Func;
            Cmd = new byte[length + 4];
            Cmd[0] = HEADER0;
            Cmd[1] = HEADER1;
            Cmd[2] = (byte)length;
            Cmd[3] = Func;
        }

        public abstract byte[] GetCmd();

        protected void CalXOR(byte[] cmd)
        {
            byte xor = cmd[2];
            for (int i = 3; i < cmd.Length - 1; i++)
            {
                xor ^= cmd[i];
            }
            cmd[cmd.Length - 1] = xor;
        }
    }
}
